package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @auth shanyue
 * @date 2025年06月06日14:01
 */
@Controller
public class AuthController {

    @Resource
    private UserService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/register")
    public String register(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/doRegister")
    public String doRegister(User user, Model model) {
        if (userService.findByUsername(user.getUsername()) != null) {
            model.addAttribute("error", "用户名已存在！");
            return "register";
        }
        user.setRole("USER");
        boolean success = userService.addUser(user);
        if (success) {
            model.addAttribute("message", "注册成功，请登录！");
            return "login";
        }
        model.addAttribute("error", "注册失败，请重试！");
        return "register";
    }

    @GetMapping("/admin/home")
    public String adminHome() {
        return "admin/home";
    }

    @GetMapping("/user/home")
    public String userHome() {
        return "user/home";
    }

}
